package com.jason.quectel0805.activities;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.jason.quectel0805.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NetActivity extends AppCompatActivity {
    private static final String TAG = "jasonwan";
    private Button btnGetNetData;

    //private Handler mHandler = new Handler(Looper.getMainLooper()) {
    //    @Override
    //    public void handleMessage(@NonNull Message msg) {
    //        super.handleMessage(msg);
    //    }
    //};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net);
        btnGetNetData = findViewById(R.id.btn_getNetData);

    }

    /**
     * 获取网络数据内容并展示
     *
     * @param view
     */
    public void getNetData(View view) {
        getNetDataByAysn();
        //Executors.newCachedThreadPool().execute(new Runnable() {
        //    @Override
        //    public void run() {
        //        getNetDataByOkHttp();
        //    }
        //});
        //new Thread(new Runnable() {
        //    @Override
        //    public void run() {
        //        getNetDataByOkHttp();
        //    }
        //}).start();
    }


    /**
     * 同步请求
     */
    public void getNetDataByOkHttp() {
        String address = "https://www.baidu.com";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String content = response.body().string();
            Log.d(TAG, "getNetDataByOkHttp: content=" + content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 异步请求,但是仍然是在子线程执行的onFailure()和onResponse()回调方法
     */
    public void getNetDataByAysn() {
        String address = "https://www.baidu.com";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: 当前线程：" + Thread.currentThread().getName());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "onResponse: 当前线程：" + Thread.currentThread().getName());
                String content = response.body().string();
                //使用View的post方法切换线程
                //btnGetNetData.post(new Runnable() {
                //    @Override
                //    public void run() {
                //
                //    }
                //});
                //使用Activity提供的runOnUiThread()方法切换线程
                NetActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "onResponse->run: " + Thread.currentThread().getName());
                        Toast.makeText(NetActivity.this, "请求成功：" + content, Toast.LENGTH_SHORT).show();
                    }
                });
                //使用Handler切换线程
                //mHandler.post(new Runnable() {
                //    @Override
                //    public void run() {
                //        try {
                //            Toast.makeText(NetActivity.this, "请求成功：" + response.body().string(), Toast.LENGTH_SHORT).show();
                //        } catch (IOException e) {
                //            e.printStackTrace();
                //        }
                //    }
                //});
                //Message obtain = Message.obtain();
                //mHandler.sendMessage(obtain);

            }
        });
        //String content = response.body().string();
        //Log.d(TAG, "getNetDataByOkHttp: content=" + content);
    }

    /**
     * 通过HttpUrlConnetion获取网络数据
     */
    public void getNetDataByHttpUrlConnection() {
        String address = "https://www.baidu.com";
        //    构建Url对象
        try {
            URL url = new URL(address);
            HttpURLConnection connection = ((HttpURLConnection) url.openConnection());
            //Android当中比较常用的两种请求方式：GET和POST
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(true);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                //    响应码=200，代表服务请响应了我们的请求并且返回了响应数据
                InputStream inputStream = connection.getInputStream();
                String content = getStrFromInputStream(inputStream);
                Log.d(TAG, "getNetData: content=\n" + content);
            } else {
                InputStream errorStream = connection.getErrorStream();
                String errorMsg = getStrFromInputStream(errorStream);
                Log.d(TAG, "error: \n" + errorMsg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将输入流转成字符串
     *
     * @param inputStream
     * @return
     */
    public String getStrFromInputStream(InputStream inputStream) {
        if (inputStream == null) {
            return "";
        }
        try {
            int result = 0;
            StringBuilder sb = new StringBuilder();
            while ((result = inputStream.read()) != -1) {
                sb.append(((char) result));
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}